<template>
    <div class="mapss">
      <div id="container" class="mymap">

        <div id="show" v-if="item.name">
          <div class="wrap_head">
            <div class="title">
              {{ item.name }}
            </div>

          </div>
          <div class="wrap_mid">
            <div class="address">
              联系地址：{{ item.address }}
            </div>
          </div>
          <div class="wrap_mid">
            <div class="address">
              联系电话：{{ item.tel }}
            </div>
            <a href="item.tel" class="call">电话咨询</a>

          </div>
          <div class="wrap_bottom">
              营业时间：{{ item.tradetime }}
          </div>
        </div>
      </div>
      <ul v-show="false" id="my-list">

      </ul>
    </div>
</template>
<script>

import AMap from 'AMap';   //在页面中引入高德地图
import bus from '../js/bus'

var this_;
// function ihide (e){
//   e.stopPropagation();
//   console.log(this_);
//   this_.bol=!this_.bol;
// }

export default {
    data(){
      return {
        data:[],
        item:{},
        bol:false,
        result:0,
        cases:1
      }
    },
    created(){
      this.cases = this.$route.query.key;
      console.log(this.$route.query.key+'sssssssssssssssssssssssss');
      switch (this.cases) {
        case 0:
        case 1:this.axios.get('http://txspring.cn:8080/getBj').then(response=>{
          // console.log(response.data.data.storeList);
            this.data = response.data.data.storeList;
        })

        break;
        case 2:this.axios.get('http://txspring.cn:8080/getSj').then(response=>{
          // console.log(response.data.data.storeList);
            this.data = response.data.data.storeList;
        })

            break;
        case 3:this.axios.get('http://txspring.cn:8080/getpx').then(response=>{
          // console.log(response.data.data.storeList);
            this.data = response.data.data.storeList;
        })

              break;
        default:this.axios.get('http://txspring.cn:8080/getBj').then(response=>{
          // console.log(response.data.data.storeList);
            this.data = response.data.data.storeList;
        })

      }
      this.result = this.$route.query.name;

      console.log(this.cases);
      // 收取车上的信息 经验证路由跳转的最好用路由传值。
      // bus.$on('storel',data=>{
      //   console.log(data + 'llal');
      //   this.result = data;
      // })
    },
    mounted(){
      this_ = this;
      this.axios.get('http://webapi.amap.com/maps?v=1.4.1&key=e19ded39d2e04fb3a2c8feb252f03c0c').then(response=>{
        // console.log(response.data.data.storeList);
        if (window.AMap && window.AMapUI) {
          this.$nextTick(function(){
            this.loadmap(this_);//加载地图和相关组件
          })
       // 未载入高德地图API，则先载入API再初始化
       }
     })


    },
    methods: {
      loadmap(this_){
        var map = new AMap.Map('container', {
          zoom: 9,
          resizeEnable: true
        });
        var geolocation;
        //加载地图，调用浏览器定位服务

        map.plugin('AMap.Geolocation', function() {
            geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,//是否使用高精度定位，默认:true
                timeout: 10000,          //超过10秒后停止定位，默认：无穷大
                buttonOffset: new AMap.Pixel(33, 300),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
                zoomToAccuracy: false,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                buttonPosition:'LM'
            });
            map.addControl(geolocation);
            if (this_.cases!=0 && this_.cases!=1&& this_.cases!=2&& this_.cases!=3){
              console.log('触发定位');
              geolocation.getCurrentPosition();
              AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
              AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
            }
        });
        //解析定位结果
        function onComplete(data) {
            var str=['定位成功'];
            str.push('经度：' + data.position.getLng());
            str.push('纬度：' + data.position.getLat());
            if(data.accuracy){
                 str.push('精度：' + data.accuracy + ' 米');
            }//如为IP精确定位结果则没有精度信息
            str.push('是否经过偏移：' + (data.isConverted ? '是' : '否'));
           //  document.getElementById('my-list').innerHTML = str.join('<br>');
        }
        //解析定位错误信息
        function onError(data) {
           //  document.getElementById('my-list').innerHTML = '定位失败';
        }
        AMapUI.loadUI(['misc/MarkerList','control/BasicControl'], function(MarkerList,BasicControl) {
            //启动页面
            initPage(MarkerList,BasicControl);

        });

        function initPage(MarkerList,BasicControl) {
            //创建一个实例
            map.addControl(new BasicControl.Zoom({
                position: 'rm', //left top，左上角
                showZoomNum: false //显示zoom值
            }));
            var markerList = new MarkerList({
                map: map, //关联的map对象
                listContainer: 'my-list', //列表的dom容器的节点或者id, 用于放置getListElement返回的内容
                getDataId: function(dataItem, index) {
                    //返回数据项的Id
                    return dataItem.id;
                },
                getPosition: function(dataItem) {
                    //返回数据项的经纬度，AMap.LngLat实例或者经纬度数组
                    return dataItem.position;
                },
                getMarker: function(dataItem, context, recycledMarker) {
                    var content = '',
                        label = {
                            offset: new AMap.Pixel(16, 18),
                            content: content
                        };

                    if (recycledMarker) {
                        //存在可回收利用的marker,直接setLabel返回
                        recycledMarker.setLabel(label);
                        return recycledMarker;
                    }
                    //返回一个新的Marker
                    return new AMap.Marker({
                        label: label
                    });
                },
                getInfoWindow: function(dataItem, context, recycledInfoWindow) {
                    var tpl = '<p><%- dataItem.id %><br><%- dataItem.desc %><p>';
                    //MarkerList.utils.template支持underscore语法的模板
                    var content = MarkerList.utils.template(tpl, {
                        dataItem: dataItem,
                        dataIndex: context.index,

                    });
                    if (recycledInfoWindow) {
                        //存在可回收利用的infoWindow, 直接setContent返回
                        recycledInfoWindow.setContent(content);
                        return recycledInfoWindow;
                        console.log(recycledInfoWindow);
                    }
                    //返回一个新的InfoWindow
                    return new AMap.InfoWindow({
                        offset: new AMap.Pixel(0, -23),
                        content: content
                    });
                },
                getListElement: function(dataItem, context, recycledListElement) {
                    var tpl = '<div id="show">'+
                      '<div class="wrap_head">'+
                        '<div class="title"><%- dataItem.id %></div>'+
                        '</div><div class="wrap_mid"><div class="address">联系地址：<%- dataItem.desc %></div></div>'+
                      '<div class="wrap_mid"><div class="address">联系电话：<%- dataItem.tel %></div>'+
                        '<a href="item.tel" class="call">电话咨询</a></div>'+
                        '<div class="wrap_bottom"> 营业时间：<%- dataItem.id %>  </div></div>';
                    var content = MarkerList.utils.template(tpl, {
                        dataItem: dataItem,
                        dataIndex: context.index
                    });
                    if (recycledListElement) {
                        //存在可回收利用的listElement, 直接更新内容返回
                        recycledListElement.innerHTML = content;
                        return recycledListElement;
                    }
                    //返回一段html，MarkerList将利用此html构建一个新的dom节点
                    return '<li>' + content + '</li>';
                }
            });
            //监听Marker和ListElement上的点击，详见markerEvents，listElementEvents
            markerList.on('markerClick listElementClick', function(event, record) {
              let inde = record.index;
              // console.log(event);
              // console.log(record);
              this_.item = this_.data[inde];
              this_.bol=true;
            });

            //监听选中改变
            markerList.on('selectedChanged', function(event, info) {
              console.log(info);
              console.log(event);
              // if(info.selectAgain == true){
              //   console.log(1111111111);
              //   this_.item==null;
              //
              // }
            });



            //构建数据源，数据项本身没有格式要求，但需要支持getDataId和getPosition
            var data = [];
            for (var i = 0; i < this_.data.length; i++) {
              data.push({
                id:this_.data[i].name,
                desc:this_.data[i].address,
                tel:this_.data[i].tel,
                position:[this_.data[i].xcoord,this_.data[i].ycoord]
              })

            }

            //绘制数据源，Let's go!
            markerList.render(data);
            var lists = document.querySelectorAll('#my-list')
            markerList.on('renderComplete',lists=>{
              if(this_.result!=null){
                console.log(this_.result);
                var list = document.querySelectorAll('#my-list>li')[this_.result]
                console.log(list+'点击事件触发');
                if (list) {
                  list.click();
                }

              }
            })

            //清除数据
            //markerList.render([]);
        }

      }
    },
    watch:{
      '$routes'(newValue,oldValue){
        console.log('_________________________________________________________');
        console.log(newValue.query.name);
        this.n = newValue.query.name;
      }
    }
}
</script>
<style scoped>
    .mymap{
      width:100%;
      height:;
    }
    .amap-info-outer{
      width: 80%;
    }
    #container{
      height: 60rem;
    }
    #show{
      position: fixed;
      bottom: 0;
      right: 0;
      left: 0;
      height: 13rem;
      color: white;
      background-color: rgba(0, 0, 0, 0.5);
      z-index: 1000;
      text-align: left;
      line-height: 2.3rem;
      padding-left: 2.1rem;
    }
    .call{
      background-color: orange;
      color: white;
      padding: .2rem .6rem;
      float: right;
    }
</style>
